package com.fzy.core;

import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.LinkedList;
import java.util.List;

import org.apache.log4j.Logger;
import org.springframework.jdbc.core.ResultSetExtractor;
import org.springframework.jdbc.core.RowMapper;

public class MyRowMapperResultSetExtractor implements ResultSetExtractor {
	protected final Logger log = Logger.getLogger(getClass());
	RowMapper rowMapper;
	Page page;

	public MyRowMapperResultSetExtractor(RowMapper rowMapper, Page page) {
		this.rowMapper = rowMapper;
		this.page = page;
	}

	public Object extractData(ResultSet rs) throws SQLException {
		List results = new LinkedList();
//		int rowNum = 0;
		if (page == null || !page.isParamCorrect()) {
			// while (rs.next()) {
			// results.add(this.rowMapper.mapRow(rs, rowNum++));
			// }
		} else {
			rs.last();
			page.setTotalCount(rs.getRow());
			int pageNo = page.getPageNo();
			int pageSize = page.getPageSize();
			int beforeCurrentPageFirst = ((pageNo - 1) * pageSize);
			if (beforeCurrentPageFirst == 0)
				rs.beforeFirst();
			else
				rs.absolute(beforeCurrentPageFirst);
			
			int count = 0;
			while (rs.next() && count < pageSize) {
				count++;
				results.add(this.rowMapper.mapRow(rs, beforeCurrentPageFirst + count));
			}
			page.setResult(results);

		}
		return page;
	}

}
